import { ObjectType } from '@src/types';
import { isNameExp } from '../../utils';
import {
  ValidationOptions,
  registerDecorator,
  ValidationArguments,
  Validator,
  isMobilePhone,
  isEmail,
} from 'class-validator';

export const IsValidationName = (validationOptions: ValidationOptions = {}): any => {
  const validator = new Validator();
  //用于dto上校验用户输入的用户名、邮箱、手机号码
  validationOptions = {
    ...validationOptions,
    ...{ message: '请输入有效的用户名/手机号码/邮箱' },
  };
  return (object: ObjectType, propertyName: string) => {
    registerDecorator({
      name: 'isValidationName',
      target: object.constructor,
      propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          if (validationOptions.each) {
            for (const item of value) {
              if (!isValidationName(item)) {
                return false;
              }
            }
            return true;
          }
          return isValidationName(value);
        },
      },
    });
  };
};

//根据正则校验用户名是否满足手机号码、邮箱、用户名的标准
const isValidationName = (value: string): boolean => {
  const validator: Validator = new Validator();
  if (
    isMobilePhone(value, 'zh-CN') ||
    isEmail(value) ||
    isNameExp.test(value)
  ) {
    return true;
  } else {
    return false;
  }
};
